package com.jc.utils;

import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @author wangli
 * @create 2016-09-22 11:23
 * @description dao层常用工具类
 */

public class DaoUtils {

    public static void buildConditionsByReflect(Object criteria, Object reflect) {

        Field[] fields = reflect.getClass().getDeclaredFields();

        for (Field field : fields) {
            String varName = field.getName();

            try {

                boolean accessFlag = field.isAccessible();
                if (!accessFlag) field.setAccessible(Boolean.TRUE);
                field.setAccessible(Boolean.TRUE);

                Object varValue = field.get(reflect);
                //筛选出domain里面,非空字段,以及serialVersionUID字段
                if (null != varValue && !varName.contains("serialVersionUID")) {

                    StringBuilder sb = new StringBuilder().append("and").append(StringUtils.capitalize(varName)).append("EqualTo");
                    Method[] methods = criteria.getClass().getMethods();

                    for (Method method : methods) {
                        String methodName = method.getName();
                        //执行criteria.and***EqualTo(***)方法
                        //例如 criteria.andOptTagEqualTo(tag);
                        if (methodName.contains(sb)) {
                            method.invoke(criteria, varValue);
                            break;
                        }
                    }

                }

                if (!accessFlag) field.setAccessible(false);

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}
